package com.qf.micrograss.like.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.common.core.entity.LikeInfo;
import com.qf.common.core.utils.DateUtils;
import com.qf.common.core.utils.UserUtils;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.micrograss.grass.service.GrassService;
import com.qf.micrograss.like.mapper.LikeMapper;
import com.qf.micrograss.like.service.LikeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * --- 缘分让我们相遇乱世以外 ---
 *
 * @author SJY
 * 2025/1/6
 */
@Service
public class LikeServiceImpl implements LikeService {

    @Resource
    private LikeMapper likeMapper;
    @Resource
    private GrassService grassService;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 点赞、取消点赞
     */
    @Override
    public void like(Integer articleId) {
        Integer uid = UserUtils.getUid();
        LikeInfo likeInfo = likeMapper.selectOne(new LambdaQueryWrapper<LikeInfo>()
                .eq(LikeInfo::getUid, uid)
                .eq(LikeInfo::getGrassId, articleId));
        if (likeInfo == null) { // 未点赞
            likeInfo = new LikeInfo();
            likeInfo.setUid(uid);
            likeInfo.setGrassId(articleId);
            likeMapper.insert(likeInfo);
            grassService.updateLikeNum(articleId, 1);
        } else { // 取消点赞
            likeMapper.deleteById(likeInfo.getId());
            grassService.updateLikeNum(articleId, -1);
        }
    }

    @Override
    public void like2(Integer articleId) {
        // 本例都是使用redis进行操作,点赞或者取消点赞,都需要和redis进行交互,针对该情况可以进一步优化
        // 优化思路:lua脚本,保证代码的一致性,减少网络IO,提高性能
        // 判断是否点赞,redis
        // 使用redis考虑数据类型,以及key值
        // 本例使用hash存储数据 考虑 key field value,key为文章id,field为用户id,value为点赞状态
        Integer uid = UserUtils.getUid();
        String likeKey = String.format("like:%s", articleId);
        Integer v = redisUtil.getCacheMapValue(likeKey, uid.toString());
        // 如果没有点赞,增加点赞记录,并增加点赞数
        // 当天的点赞数,也存在redis中,本例使用hash存储数据,key likeNum:当天年月日,field为文章id,value为点赞数
        String likeNumKey = String.format("likeNum:%s", DateUtils.formatLocalDate(LocalDate.now(), "yyyyMMdd"));
        if (v == null) {
            redisUtil.setCacheMapValue(likeKey, uid.toString(), 1);
            redisUtil.incrCacheMapValue(likeNumKey, articleId.toString(), 1);
        } else { // 否则,删除点赞记录,并减去点赞数
            redisUtil.delCacheMapValue(likeKey, uid.toString());
            redisUtil.incrCacheMapValue(likeNumKey, articleId.toString(), -1);
        }
    }
}
